package com.example.navigationdemo.nav;

import android.os.Bundle;
import android.os.PersistableBundle;
import android.text.TextUtils;
import android.view.MenuItem;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.navigation.NavController;
import androidx.navigation.fragment.NavHostFragment;
import com.example.navigationdemo.R;
import com.example.navigationdemo.nav.model.Destination;
import com.example.navigationdemo.nav.utils.AppConfig;
import com.example.navigationdemo.nav.utils.NavGraphBuilder;
import com.example.navigationdemo.nav.view.AppBottomBar;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author: tuyrt7 on 2020/9/3.
 */
public class NavigationActivity extends AppCompatActivity implements BottomNavigationView.OnNavigationItemSelectedListener {

    private NavController mNavController;
    private AppBottomBar mBottomBar;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_navigation);
        mBottomBar = findViewById(R.id.bottom_bar);

        /**
         *  关联配置文件和 Navigation
         */
        Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.nav_host);
        mNavController = NavHostFragment.findNavController(fragment);
        NavGraphBuilder.build(this, fragment.getChildFragmentManager(), mNavController, fragment.getId());

        mBottomBar.setOnNavigationItemSelectedListener(this);
    }

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem menuItem) {
        HashMap<String, Destination> destConfig = AppConfig.getDestConfig();
        Iterator<Map.Entry<String, Destination>> iterator = destConfig.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, Destination> next = iterator.next();
            Destination destination = next.getValue();
            //还要判断是否当前已登录
            if (destination != null && !isLogin() && destination.needLogin && menuItem.getItemId() == destination.id) {
                //TODO ** 去登录监听返回结果，登录成功后
                mBottomBar.setSelectedItemId(menuItem.getItemId());
            }
        }

        mNavController.navigate(menuItem.getItemId());
        return !TextUtils.isEmpty(menuItem.getTitle());
    }

    private boolean isLogin() {
        return true;
    }

    /**
     * 当MainActivity因为内存不足或系统原因 被回收时 会执行该方法。
     * <p>
     * 此时会触发 FragmentManangerImpl#saveAllState的方法把所有已添加的fragment基本信息给存储起来(view没有存储)，以便于在恢复重建时能够自动创建fragment
     * <p>
     * 但是在fragment嵌套fragment的情况下，被内嵌的fragment在被恢复时，生命周期被重新调度，出现了错误。没有重新走onCreateView 方法
     * 从而会触发throw new IllegalStateException("Fragment " + fname did not create a view.");的异常
     * <p>
     * 但是在没有内嵌fragment的情况，没有问题、
     * <p>
     * <p>
     * 那我们为了解决这个问题，网络上也有许多方案，但都不尽善尽美。
     * <p>
     * 此时我们复写onSaveInstanceState，不让 FragmentManangerImpl 保存fragment的基本数据，恢复重建时，再重新创建即可
     *
     * @param outState
     */
    @Override
    public void onSaveInstanceState(@NonNull Bundle outState, @NonNull PersistableBundle outPersistentState) {
        //super.onSaveInstanceState(outState, outPersistentState);
    }

    @Override
    public void onBackPressed() {
        int currentId = mNavController.getCurrentDestination().getId();
        int homeId = mNavController.getGraph().getStartDestination();
        //不是起始节点，就退回起始节点
        if (currentId != homeId) {
            mBottomBar.setSelectedItemId(homeId);
            return;
        }
        finish();
    }
}
